package com.cn.jdia.tas.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cn.jdia.tas.model.T_attrecord;
import com.cn.jdia.tas.model.T_employee;
import com.cn.jdia.tas.model.U_department;
import com.cn.jdia.tas.service.IAttrecordService;
import com.cn.jdia.tas.service.IDepartmentService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Controller
@RequestMapping("/control")
public class LatercheckPersonController {

	@Resource
	private IDepartmentService deptService = null;

	@Resource
	private IAttrecordService attrecordService = null;

	@RequestMapping("/latercheckperson")
	public String getLatercheckPerson(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String data = request.getParameter("data");
		Gson gson = new Gson();
		Map<String, String> pmap = gson.fromJson(data, new TypeToken<Map<String, String>>() {
		}.getType());

		String deptid = pmap.get("deptid");
		DateTime dt = new DateTime();
		String date = dt.toString("YYYY-MM-dd");
		// System.out.println(deptid + " " + date);

		List<U_department> subDeptInfo = deptService.getSubDeptInfo(deptid);
		List<T_attrecord> lateRecordList = null;
		if (subDeptInfo.size() == 0) {
			lateRecordList = attrecordService.getChildDeptLateRecord(date, deptid);
		} else { // 含专业线情况
			lateRecordList = attrecordService.getParentDeptLateRecord(date, deptid);
		}

		List<Map<String, String>> rlist = new ArrayList<>();
		Map<String, String> rmap;
		List<String> idlist = new ArrayList<>();

		if (lateRecordList.size() != 0) {
			for (T_attrecord att : lateRecordList) {
				if (idlist.contains(att.getEmployeeid())) {
					continue;
				}

				rmap = new HashMap<>();
				rmap.put("name", att.getEmployee().getEmployeename());
				rmap.put("time", att.getChecktime());
				rmap.put("loc", att.getAttmachinename());

				rlist.add(rmap);
				idlist.add(att.getEmployeeid());
			}
		}

		out.write(gson.toJson(rlist));
		out.flush();
		out.close();

		return null;
	}

}
